package com.xgq.drink.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.easysdk.factory.Factory;
import com.xgq.drink.config.AliPayConfig;
import com.xgq.drink.entity.AliPay;
import com.xgq.drink.entity.Orders;
import com.xgq.drink.entity.Payment;
import com.xgq.drink.service.IOrderService;
import com.xgq.drink.service.IPaymentService;
import com.xgq.drink.utils.UniqueIdGenerator;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
@Tag(name = "支付模块", description = "支付相关接口")
public class AliPayController {

    @Autowired
    private AliPayConfig aliPayConfig;  // 确保这里不是 static
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IPaymentService paymentService;
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @GetMapping("/pay")
    public void pay(@Parameter String traceNo, HttpServletResponse httpResponse, HttpServletRequest request2) throws Exception {
        // 根据 traceNo 获取订单
        System.out.println("根据 traceNo 获取订单");
        Orders order = orderService.getOrderById(traceNo);
        if (order == null) {
            throw new RuntimeException("订单不存在！");
        }
        // 检查订单状态是否为待付款
        System.out.println("检查订单状态是否为待付款222"+order.getStatus());
        if (order.getStatus() != 1) {
            throw new RuntimeException("订单状态不允许支付！");
        }
        System.out.println("AliPay");
        AliPay aliPay = new AliPay();
        aliPay.setTraceNo(traceNo);
        aliPay.setTotalAmount(order.getPayAmount());
        aliPay.setSubject("共有"+order.getProductNum()+"件商品！");
        System.out.println("开始执行支付操作");
        // 创建支付记录，状态设置为“支付中”
        Payment payment = new Payment();
        payment.setPaymentId(UniqueIdGenerator.generateUniqueId());
        payment.setOrderId(order.getOrderId());
        payment.setPaymentMethod("支付宝");
        payment.setPaymentAmount(order.getPayAmount());
        payment.setPaymentStatus(0); // 设置为支付中
        paymentService.savePayment(payment);
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\"," +
                "\"total_amount\":\"" + aliPay.getTotalAmount() + "\"," +
                "\"subject\":\"" + aliPay.getSubject() + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        Payment payment = new Payment();
        System.out.println("=========支付宝异步回调========");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        String tradeNo = params.get("out_trade_no");
        // 增加严格验签
        if (!Factory.Payment.Common().verifyNotify(params)) {
            return "fail";
        }

        // 增加重复通知检查
        String notifyId = params.get("notify_id");
        if (paymentService.isNotifyProcessed(notifyId)) {
            return "success"; // 幂等处理
        }
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            // 获取订单和支付记录
            Orders order = orderService.getOrderById(tradeNo);
            payment = paymentService.getPaymentByOrderId(order.getOrderId());
            if (order == null || payment == null) {
                return "fail"; // 订单或支付记录不存在
            }
            if (Factory.Payment.Common().verifyNotify(params)) {
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            }
            // 更新订单状态为“待发货”
            order.setStatus(2);
            System.out.println("订单状态为："+order.getStatus());
            System.out.println("订单id为："+order.getOrderId());
            System.out.println("订单支付金额为："+order.getPayAmount());
            orderService.updateOrderStatus(order);
            //支付成功
            payment.setPaymentStatus(2);
            payment.setBuyer_id(params.get("buyer_id"));
            payment.setVoucher(params.get("trade_no"));
            // 假设 params 是一个 Map，包含交易参数
            String gmtPayment = params.get("gmt_payment"); // 获取时间字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            payment.setPaymentTime(LocalDateTime.parse(gmtPayment, formatter));
            paymentService.updatePayment(payment);
        }else if ("TRADE_CLOSED".equals(request.getParameter("trade_status"))) {
            tradeNo = params.get("trade_no");
            payment = paymentService.getPaymentByVoucher(tradeNo);
            if (payment != null) {
                payment.setPaymentStatus(3); // 3:已退款
                paymentService.updatePayment(payment);
            }
        }else {
            //支付失败
            payment.setPaymentStatus(1);
            paymentService.updatePayment(payment);
            return "fail";
        }
        return "success";
    }
}